package com.txzt.gaea.archive.service.impl;

import com.txzt.base.constant.RtnConstant;
import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.api.client.AdminUserRemoteService;
import com.txzt.gaea.archive.dto.BizArchiveDTO;
import com.txzt.gaea.archive.model.BizArchive;
import com.txzt.gaea.archive.model.BizArchiveRecord;
import com.txzt.gaea.archive.service.BizArchiveService;
import com.txzt.gaea.archive.vo.BizArchiveRecordVo;
import com.txzt.gaea.archive.vo.BizArchiveVo;
import com.txzt.gaea.base.model.DictInfo;
import com.txzt.gaea.business.util.TranslateUtil;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.enums.ArchiveStatusEnum;
import com.txzt.gaea.common.enums.IsDeleteEnum;
import com.txzt.gaea.common.page.PageInfoBT;
import com.txzt.gaea.dto.UserSingleDetailQueryDTO;
import com.txzt.gaea.provide.service.biz.DeptApiService;
import com.txzt.gaea.vo.ZTreeNodeVO;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.formula.functions.T;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Service
public class BizArchiveServiceImpl extends BaseServiceImpl<BizArchive> implements BizArchiveService {
    @Autowired
    private AdminUserRemoteService adminUserRemoteService;
    @Autowired
    private DeptApiService deptApiService;

    @Override
    public Map<String, Object> statisticsBizArchive() {
        Long total = sqlManager.allCount(BizArchive.class);

        List<Map> mapType = sqlManager.select("bizArchive.statisticsType",Map.class,null);

        List<Map> mapList = sqlManager.select("bizArchive.statisticsBizArchive",Map.class,null);
        mapList.forEach(map ->{
            map.put("departName", TranslateUtil.getDepartmentName(Long.parseLong(map.get("deptId").toString())));
        });

        Map<String, Object> map = new HashMap();
        map.put("total",total);
        map.put("mapType",mapType);
        map.put("mapList",mapList);
        return map;
    }

    @Override
    public RtnInfo<PageInfoBT<BizArchiveVo>> pageList(BizArchiveDTO bizArchiveDTO){
        List<ZTreeNodeVO> deptList = deptApiService.deptInfoList();
        PageQuery<BizArchiveVo> pageQuery = new PageQuery<>(bizArchiveDTO.getOffset(),
                bizArchiveDTO.getLimit(), bizArchiveDTO);
        PageQuery<BizArchiveVo> result =
                this.sqlManager.pageQuery("bizArchive.selectPageList", BizArchiveVo.class, pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT<>(result));
        }
        result.getList().forEach(item -> {
            UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
            userSingleDetailQueryDTO.setUserId(item.getCreateBy());
            item.setCreateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            userSingleDetailQueryDTO.setUserId(item.getUpdateBy());
            item.setUpdateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            if (null != item.getBorrowBy()){
                userSingleDetailQueryDTO.setUserId(item.getBorrowBy());
                item.setBorrowName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            }
            String deptName = null;
            if (null != item.getDepartId()){
                for (ZTreeNodeVO z : deptList) {
                    if (Long.parseLong(z.getId()) == item.getDepartId()){
                        deptName = z.getName();
                        break;
                    }
                }
            }
            item.setDepartName(deptName);
        });
        PageInfoBT<BizArchiveVo> re = new PageInfoBT<>(result);
        rebuild(re);
        return RtnInfo.success(re);
    }

    private void rebuild(PageInfoBT<BizArchiveVo> re){
        List<BizArchiveVo> list = re.getRows();
        if(CollectionUtils.isEmpty(list)){
            re.setTotal(0);
            return;
        }
//        re.setTotal(list.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(BizArchive bizArchive){
        bizArchive.setFilingDate(new Date());
        bizArchive.setStatus(ArchiveStatusEnum.RECORD.getCode());
        return this.sqlManager.insert(bizArchive);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(BizArchive bizArchive){
        return this.sqlManager.updateTemplateById(bizArchive);
    }

    @Override
    public boolean addCheckName(BizArchive bizArchive){
        LambdaQuery<BizArchive> query = sqlManager.lambdaQuery(BizArchive.class);
        List<BizArchive> orgList = query.andEq(BizArchive::getArchiveName,bizArchive.getArchiveName())
                .andEq(BizArchive::getIsDelete,IsDeleteEnum.NOTDELETE.getCode()).select();
        return 0 >= orgList.size();
    }

    @Override
    public boolean updateCheckName(BizArchive bizArchive){
        LambdaQuery<BizArchive> query = sqlManager.lambdaQuery(BizArchive.class);
        List<BizArchive> orgList = query.andEq(BizArchive::getArchiveName,bizArchive.getArchiveName())
                .andEq(BizArchive::getIsDelete, IsDeleteEnum.NOTDELETE.getCode())
                .andNotEq(BizArchive::getId,bizArchive.getId()).select();
        return 0 >= orgList.size();
    }

    @Override
    public int delete(Long id){
        BizArchive bizArchive = new BizArchive();
        bizArchive.setId(id);
        bizArchive.setIsDelete(IsDeleteEnum.DELETE.getCode());
        return this.sqlManager.updateTemplateById(bizArchive);
    }

    @Override
    public RtnInfo<BizArchive> getInfo(Long id){
        BizArchive bizArchive = this.selectById(id);
        if (null == bizArchive){
            return RtnInfo.error(RtnConstant.Code.PARAMS_REEOR,"未查到相关信息，请检查上传数据是否正确");
        } else {
            return  RtnInfo.success(bizArchive);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean borrowArchive(BizArchiveDTO param){
        BizArchive bizArchive = this.selectById(param.getId());
        bizArchive.setBorrowDate(new Date());
        bizArchive.setBorrowBy(param.getBorrowBy());
        bizArchive.setStatus(ArchiveStatusEnum.BORROW.getCode());
        this.sqlManager.updateTemplateById(bizArchive);
        BizArchiveRecord bizArchiveRecord = new BizArchiveRecord();
        bizArchiveRecord.setArchiveId(param.getId());
        bizArchiveRecord.setComment(param.getComment());
        bizArchiveRecord.setBorrowBy(param.getBorrowBy());
        bizArchiveRecord.setBorrowDate(bizArchive.getBorrowDate());
        this.sqlManager.insert(bizArchiveRecord);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean returnArchive(BizArchiveDTO param){
        BizArchive bizArchive = this.selectById(param.getId());
        bizArchive.setReturnDate(new Date());
        bizArchive.setStatus(ArchiveStatusEnum.RECORD.getCode());
        this.sqlManager.updateTemplateById(bizArchive);
        LambdaQuery<BizArchiveRecord> query = sqlManager.lambdaQuery(BizArchiveRecord.class);
        BizArchiveRecord bizArchiveRecord = query.andEq(BizArchiveRecord::getArchiveId,bizArchive.getId())
                .orderBy("borrow_date desc").single();
        bizArchiveRecord.setReturnDate(bizArchive.getReturnDate());
        this.sqlManager.updateTemplateById(bizArchiveRecord);
        return true;
    }

    @Override
    public RtnInfo<PageInfoBT<BizArchiveRecordVo>> pageRecordList(BizArchiveDTO bizArchiveDTO){
        PageQuery<BizArchiveRecordVo> pageQuery = new PageQuery<>(bizArchiveDTO.getOffset(),
                bizArchiveDTO.getLimit(), bizArchiveDTO);
        PageQuery<BizArchiveRecordVo> result =
                this.sqlManager.pageQuery("bizArchive.selectRecordPageList", BizArchiveRecordVo.class, pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT<>(result));
        }
        result.getList().forEach(item -> {
            UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
            userSingleDetailQueryDTO.setUserId(item.getBorrowBy());
            item.setBorrowName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
        });
        PageInfoBT<BizArchiveRecordVo> re = new PageInfoBT<>(result);
        rebuildRecord(re);
        return RtnInfo.success(re);
    }

    private void rebuildRecord(PageInfoBT<BizArchiveRecordVo> re){
        List<BizArchiveRecordVo> list = re.getRows();
        if(CollectionUtils.isEmpty(list)){
            re.setTotal(0);
            return;
        }
//        re.setTotal(list.size());
    }


}
